﻿using System;
using System.Collections.Generic;
using System.IO.Ports;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace thinger.AutomaticStoreMotionDAL
{
    public class ScannerSerial
    {
        #region 事件和字段
        //事件
        public event EventHandler SannerSerialReceived;

        //私有字段
        private SerialPort _scannerSerial;
        #endregion

        #region 连接和断开串口
        /// <summary>
        /// 连接串口
        /// </summary>
        /// <param name="baudRate">波特率</param>
        /// <param name="portName">串口号</param>
        /// <param name="parity">校验位</param>
        /// <param name="dataBits">数据位</param>
        /// <param name="stopBits">停止位</param>
        public void Connect(int baudRate, string portName, Parity parity, int dataBits, StopBits stopBits)
        {
            if (_scannerSerial == null)
            {
                _scannerSerial = new SerialPort();
            }
            if (_scannerSerial.IsOpen)
            {
                _scannerSerial.Close();
            }

            _scannerSerial.BaudRate = baudRate;
            _scannerSerial.PortName = portName;
            _scannerSerial.Parity = parity;
            _scannerSerial.DataBits = dataBits;
            _scannerSerial.StopBits = stopBits;

            _scannerSerial.ReceivedBytesThreshold = 1;
            _scannerSerial.DataReceived += _scannerSerial_DataReceived;

            _scannerSerial.Open();
        }

        /// <summary>
        /// 断开串口
        /// </summary>
        public void DisConnect()
        {
            if (_scannerSerial.IsOpen )
            {
                _scannerSerial.Close();
            }
        }
        #endregion

        #region _scannerSerial.DataReceived串口接收到数据事件触发后，执行该方法
        private void _scannerSerial_DataReceived(object sender, SerialDataReceivedEventArgs e)
        {
            try
            {
                //创建字节数组，长度为串口缓冲区的字节数据长度
                byte[] rcv = new byte[_scannerSerial.BytesToRead];
                //读取串口数据
                _scannerSerial.Read(rcv, 0, rcv.Length);
                //将字节数组解码成一个字符串
                string message = Encoding.Default.GetString(rcv);
                //替换消息里面的回车换行键
                message = message.Replace("\r\n", "");
                //触发ScannerSerial的自定义事件
                SannerSerialReceived?.Invoke(this, new SannerReceivedEventArgs(message));
            }
            catch { }
        }

        #endregion

    }

    #region 扫码串口触发的事件数据类
    public class SannerReceivedEventArgs : EventArgs
    {
        public string Message { get; set; }

        public SannerReceivedEventArgs(string message)
        {
            this.Message = message;
        }
    }

    #endregion

}
